import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '../store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // request baseUrl
  // baseURL: '/api',
  timeout: 10000 // request timeout
})
let showErrorToken = true // 多个请求token失效时候 只显示一次异常

// request interceptor
service.interceptors.request.use(
  async config => {
    if (store.getters.token) {
      config.headers['X-SERVICER-TOKEN'] = getToken() // 请求携带自定义token
    }
    // console.log('request=====>', config)

    // api鉴权
    if (Object.keys(store.getters.authorizeApi).includes(config.url) && (store.getters.authorizeApi[config.url].needAdmin && store.getters.userInfo.isAdmin || !store.getters.authorizeApi[config.url].needAdmin)) {
      return await store.state.user.authentication.open(store.getters.authorizeApi[config.url].sceneStr).then(() => {
        return config
      }).catch(() => {
        return Promise.reject()
      })
    } else {
      return config
    }
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
// response 拦截器
service.interceptors.response.use(
  response => {
    const { responseType, hideMessage, returnResult } = response.config
    // console.log('response', response)
    const res = response.data
    // console.log('response=====>', res)
    // if the custom code is not 0, it is judged as an error.
    if (returnResult) {
      return response
    } else if (responseType == 'blob') {
      return response
    } else if (res.code !== 0) {
      // 40001:非法的token
      // 40002:其他客户端登录了
      if (res.code === 40001 || res.code === 40002) {
		console.log('登录状态res.code',res.code)
        if (showErrorToken) {
          showErrorToken = false
          MessageBox.confirm(
            '登录已失效，可以取消继续留在该页面，或者重新登录',
            '确定登出',
            {
              confirmButtonText: '重新登录',
              cancelButtonText: '取消',
              type: 'warning'
            }
          ).then(() => {
            store.dispatch('user/FedLogOut').then(() => {
              location.reload()
            })
          }).catch(() => {
            showErrorToken = true
          })
        }
      } else {
        if (!hideMessage) {
          Message({
            message: res.code + ':' + res.msg,
            type: 'error',
            duration: 3 * 1000
          })
        }
      }
      return Promise.reject(res)
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message.indexOf('timeout') !== -1 ? '请求超时' : error.message,
      type: 'error',
      duration: 3 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
